import { login } from '@/api/user'
import { getToken, setToken,removeToken, getType, setType, removeType, getUser, setUser, removeUser } from '@/utils/auth' 
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: getUser(),
  avatar: '',
  roles:[],
  type: getType()
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_TYPE: (state, type) => {
    state.type = type
  }
}

const actions = {
  // user login
  login({ commit,state,dispatch }, userInfo) { 
    const { username, password } = userInfo 
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(async response => { 
        const data  = response.DATA
        commit('SET_NAME', data)
        setUser(data)
        commit('SET_AVATAR', data.avatar)
        
        commit('SET_ROLES', [data.role])   
        setToken(data.token)
        let type
        switch (data.user_type) {
          case 1:
            type = 'all'
            break;
          case 2:
            type = 'daili'
            break;
          case 3:
            type = 'qudao'
            break;
        }
        setType(type)
        commit('SET_TYPE', type)
        commit('SET_TOKEN',data.token)

        const accessRoutes = await dispatch('permission/generateRoutes', state.roles, { root: true })  
        router.addRoutes(accessRoutes)  
        
        resolve()
      }).catch(error => { 
        reject(error)
      })
    }) 
  },
 

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      removeType()
      removeUser()
      resetRouter()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

